{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook creates a dataset (images and labels as a json file). The dataset created can be used for pose classification.   \n",
    "In order to create a new dataset for gesture recoginition specify the following parameters \n",
    "\n",
    "**no_of_classes** - Number of classes to be created. i.e. For hand pose the number of hand gestures to be created.\n",
    "\n",
    "**path_dir** - Path to the directory to be created\n",
    "\n",
    "**dataset_name** - The name of the dataset to be created\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_directories_for_classes(no_of_classes, path_dir, dataset_name):\n",
    "    dir_ = os.path.join(path_dir, dataset_name)\n",
    "    for i in range(no_of_classes):\n",
    "        dir_to_create = os.path.join(dir_,\"%s\" % (i+1))\n",
    "        try:\n",
    "            os.makedirs(dir_to_create)\n",
    "        except FileExistsError:\n",
    "            print(os.path.join(\"The following directory was not created because it already exsists\", dir_ , ))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "dir_datasets = '/home/mikyas/mike_dataset/jj/'\n",
    "dataset_name = \"hand_dataset\"\n",
    "no_of_classes = 5\n",
    "create_directories_for_classes(no_of_classes, dir_datasets, dataset_name )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import ipywidgets.widgets as widgets\n",
    "dir_ = os.path.join(dir_datasets, dataset_name)\n",
    "curr_class_no = 1\n",
    "button_layout = widgets.Layout(width='128px', height='32px')\n",
    "curr_dir = os.path.join(dir_,'%s'%curr_class_no )\n",
    "collecting_button = widgets.Button(description= 'Collect Class ' + str(curr_class_no), button_style='success', layout=button_layout)\n",
    "prev_button = widgets.Button(description='Previous Class', button_style='primary', layout=button_layout)\n",
    "nxt_button = widgets.Button(description='Next Class', button_style='info', layout=button_layout)\n",
    "\n",
    "dir_count = widgets.IntText(layout=button_layout, value=len(os.listdir(curr_dir)))\n",
    "dir_count.continuous_update"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "from uuid import uuid1\n",
    "def save_snapshot(directory):\n",
    "    image_path = os.path.join(directory, str(uuid1()) + '.jpg')\n",
    "    with open(image_path, 'wb') as f:\n",
    "        f.write(image_w.value)\n",
    "def save_dir():\n",
    "    global curr_dir, dir_count\n",
    "    save_snapshot(curr_dir)\n",
    "    dir_count.value = len(os.listdir(curr_dir))\n",
    "def prev_dir():\n",
    "    global curr_class_no, curr_dir, no_of_classes\n",
    "    if curr_class_no>1:\n",
    "        curr_class_no-=1\n",
    "    curr_dir = os.path.join(dir_,'%s'%curr_class_no )\n",
    "    collecting_button.description = 'Collect Class ' + str(curr_class_no)\n",
    "    dir_count.value = len(os.listdir(curr_dir))\n",
    "    dir_count.continuous_update\n",
    "def nxt_dir():\n",
    "    global curr_class_no, curr_dir, no_of_classes\n",
    "    if curr_class_no<no_of_classes:\n",
    "        curr_class_no+=1\n",
    "    curr_dir = os.path.join(dir_,'%s'%curr_class_no )\n",
    "    collecting_button.description = 'Collect Class ' + str(curr_class_no)\n",
    "    dir_count.value = len(os.listdir(curr_dir))\n",
    "\n",
    "        \n",
    "\n",
    "collecting_button.on_click(lambda x: save_dir())\n",
    "nxt_button.on_click(lambda x: nxt_dir())\n",
    "prev_button.on_click(lambda x: prev_dir())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from jetcam.usb_camera import USBCamera\n",
    "from jetcam.csi_camera import CSICamera\n",
    "from jetcam.utils import bgr8_to_jpeg\n",
    "WIDTH = 256\n",
    "HEIGHT = 256\n",
    "camera = USBCamera(width=WIDTH, height=HEIGHT, capture_fps=30, capture_device=1)\n",
    "#camera = CSICamera(width=WIDTH, height=HEIGHT, capture_fps=50)\n",
    "\n",
    "camera.running = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ipywidgets\n",
    "from IPython.display import display\n",
    "\n",
    "image_w = ipywidgets.Image(format='jpeg', width=256, height=256)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fe359c9b5fe04069acc2f1d3549d5415",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Image(value=b'\\xff\\xd8\\xff\\xe0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\xff\\xdb\\x00C\\x00\\x02\\x01\\x0…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "025ec73f99464909b3ba3aca3fa1799c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntText(value=0, layout=Layout(height='32px', width='128px')), Button(button_style='success', d…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "71a2b3ee3ecc4ed9b66a5f9a3ee6fe02",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(Button(button_style='info', description='Next Class', layout=Layout(height='32px', width='128px…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7c858c4fc67d4a51a0143bd55bbe5068",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(Button(button_style='primary', description='Previous Class', layout=Layout(height='32px', width…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display(image_w)\n",
    "display(widgets.HBox([dir_count, collecting_button]))\n",
    "display(widgets.HBox([ nxt_button]))\n",
    "display(widgets.HBox([ prev_button]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def execute(change):\n",
    "    image = change['new']\n",
    "    image_w.value = bgr8_to_jpeg(image[:, ::-1, :])    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "execute({'new': camera.value})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "camera.observe(execute, names='value')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "camera.unobserve_all()\n",
    "camera.running = False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_labels(dir_, dataset_name):\n",
    "    labels = []\n",
    "    starting_label = 1\n",
    "    for i in range(len(os.listdir(dir_))):\n",
    "        dir_to_check = os.path.join(dir_,\"%s\" % (i+1))\n",
    "        for j in range(len(os.listdir(dir_to_check))):\n",
    "            labels.append(starting_label)\n",
    "        starting_label+=1\n",
    "    labels_to_dict = {\"labels\": labels}\n",
    "    with open((dir_+'.json'), 'w') as outfile:\n",
    "        json.dump(labels_to_dict, outfile)\n",
    "    return labels      "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rename_images(dir_):\n",
    "    overall_count = 0\n",
    "    #dir_ = dir_+dataset_name\n",
    "    for i in range(len(os.listdir(dir_))):\n",
    "        dir_to_check = os.path.join(dir_,\"%s\" % (i+1))\n",
    "        dir_to_check+='/'\n",
    "        for count, filename in enumerate(os.listdir(dir_to_check)):\n",
    "            dst = \"%08d.jpg\"% overall_count\n",
    "            src = dir_to_check+filename\n",
    "            dst = dir_to_check+dst \n",
    "            os.rename(src, dst)\n",
    "            overall_count+=1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "generate_labels(dir_, dataset_name)\n",
    "rename_images(dir_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "/home/mikyas/mike_dataset/jj/hand_dataset\n",
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'/home/mikyas/mike_dataset/jj/hand_dataset/hand_dataset.json'"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import shutil\n",
    "dir_training = dir_datasets +'/trainig/'\n",
    "try:\n",
    "    os.makedirs(dir_training)\n",
    "except FileExistsError:\n",
    "    print(os.path.join(\"The following directory was not created because it already exsists\", dir_ , ))\n",
    "for i in range(len(os.listdir(dir_))):\n",
    "    dir_to_check = os.path.join(dir_,\"%s\" % (i+1))+'/'\n",
    "    for count, filename in enumerate(os.listdir(dir_to_check)):\n",
    "            src = dir_to_check+filename\n",
    "            shutil.move(src,dir_training)\n",
    "    os.rmdir(dir_to_check)\n",
    "shutil.move(dir_training,dir_)\n",
    "shutil.move(dir_+'.json',dir_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "camera.running = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
